/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Properties;
import javax.ejb.EJB;
import javax.imageio.ImageIO;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jsonHelper.SimpleUniverse;
import service.MumuUser;
import service.Photo;
import service.PhotoCollection;
import service.Planet;
import service.Universe;
import service.UniverseFacadeREST;
import utilities.AvatarGenerator;
import utilities.ReadSmtp;

/**
 *
 * @author cristianbertuccioli
 */
public class universePublisher extends HttpServlet {
    @EJB
    private UniverseFacadeREST universeManager;
    
    private Session sessionMail;
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        
        String email = (String) session.getAttribute("validatingEmail");
        String nameSurname = (String) session.getAttribute("validatingName");
        
        final ReadSmtp readSmtp = new ReadSmtp(request);
        
        try {
            Integer universe_id = (Integer) session.getAttribute("idUniverse");
            Universe currentUniverse = universeManager.find(universe_id);
            currentUniverse.setIsReady(1);
            universeManager.edit(currentUniverse);
            
            ArrayList<SimpleUniverse> universeList = (ArrayList<SimpleUniverse>) session.getAttribute("universeList");

            Iterator<SimpleUniverse> simpleUniverseIt = universeList.iterator();
            SimpleUniverse editingUniverse = null;
            while (simpleUniverseIt.hasNext()) {
                editingUniverse = simpleUniverseIt.next();
                if (editingUniverse.getIdUniverse() == universe_id) {
                    break;
                }
            }
            editingUniverse.setIsReady(1);
            out.write("/maker.jsp?publish=1");
            out.flush();
            out.close();
//            response.sendRedirect("/maker.jsp?publish=1");
            
            // recupero mail creatore
            Collection<MumuUser> creatorList = currentUniverse.getMumuUserCollection();
            Iterator<MumuUser> creatorIt = creatorList.iterator();
            String creatorMail = "";
            String creatorName = "";
            while(creatorIt.hasNext()){
                MumuUser c = creatorIt.next();
                creatorMail = c.getMail();
                creatorName = c.getNameSurname();
                break;
            }
            
            // invio mail al creatore 
            
            Properties props = new Properties();
            props.put("mail.smtp.host", readSmtp.getSmtp_address());
            props.put("mail.smtp.socketFactory.port", readSmtp.getSmtp_port());
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", readSmtp.getAuth());
            props.put("mail.smtp.port", readSmtp.getSmtp_port());

            sessionMail = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            // email address e password
                            return new PasswordAuthentication(readSmtp.getAuth_username(), readSmtp.getAuth_password());
                        }
                    });

            try {
                InternetAddress from = new InternetAddress( email, "UniverseCreator" );
                
                Message message = new MimeMessage(sessionMail);
                message.setFrom(from);
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(creatorMail));
                message.setSubject("UniverseCreator: chiusura universo");
                String content = "Gentile " + creatorName + ",<br/><br/>"
                        + "La chiusura dell'universo: "+currentUniverse.getName()+" con codice: "+currentUniverse.getIdUniverse()+"<br/>"
                        + "&egrave; stata portata a termine in maniera corretta.<br/>"
                        + "<br/>"
                        + "La richiesta verr&agrave; presa in carico per il processo di validazione.<br/>"
                        + "Non appena il processo sar&agrave; completato, riceverai una email di notifica con il rispettivo esito.<br/>"
                        +"<br/><br/>"
                        + "<i>Staff di UniverseCreator</i>"
                        + "<br/><br/><br/>"
                        + "Non rispondere, messaggio generato in automatico da UniverseCreator.<br/>";
                message.setContent(content, "text/html");
                Transport.send(message);
            } catch (Exception e) {
                System.err.println(e.getCause());
            }
            
            // invio mail ad amministratore

            
            
            try{
                Message message = new MimeMessage(sessionMail);
                message.setFrom(new InternetAddress(readSmtp.getAuth_username()));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(readSmtp.getAuth_username()));
                message.setSubject("UniverseCreator: richiesta di validazione universo");
                String content = "Gentile Amministratore, <br/><br/>"
                        + "&Eacute; stato appena sottomesso l'universo avente:<br/>Nome: "+currentUniverse.getName()+"<br/>Codice: "+currentUniverse.getIdUniverse()+"<br/>per la validazione .<br/>"
                        + "<br/>"
                        + "Il creatore &egrave; raggiungibile al seguente indirizzo email: "+creatorMail+"<br/>"
                        + "Si suggerisce di prendere in carico la valutazione di tale universo.<br/><br/>"
                        + "<br/>"
                        + "<i>Staff di UniverseCreator</i>"
                        + "<br/><br/><br/>"
                        + "Non rispondere, messaggio generato in automatico da UniverseCreator.<br/>";
                        
                message.setContent(content, "text/html");
                Transport.send(message);
            }catch(Exception e){
                System.err.println(e.getCause());
            }
            
            // --------- GENERAZIONE NUOVO AVATAR ---------------
            
            // creo le strighe dei path che mi servono
            ArrayList<BufferedImage> universeImages = new ArrayList<BufferedImage>();
            String rootPath = request.getServletContext().getRealPath("/") + "Universes/";
            String avatarPath = rootPath + universe_id + "/";

            Universe universe = universeManager.find(universe_id);

            Collection<Planet> planets = universe.getPlanetCollection();
            Iterator<Planet> planetsIt = planets.iterator();
            Planet currentPlanet;
            File currentImage;
            while (planetsIt.hasNext()) {
                currentPlanet = planetsIt.next();
                Iterator<PhotoCollection> photoCollIt = currentPlanet.getPhotoCollectionCollection().iterator();
                PhotoCollection currentPhotoColl;
                while (photoCollIt.hasNext()) {
                    currentPhotoColl = photoCollIt.next();
                    Iterator<Photo> photoIt = currentPhotoColl.getPhotoCollection().iterator();
                    Photo currentPhoto;
                    while (photoIt.hasNext()) {
                        currentPhoto = photoIt.next();
                        System.out.println("Immagine: " + rootPath + currentPhoto.getPathPhoto());
                        currentImage = new File(rootPath + currentPhoto.getPathPhoto());
                        if (currentImage.exists()) {
                            universeImages.add(ImageIO.read(currentImage));
                        }
                    }
                }

            }

            if (universeImages.size() > 2) {
                boolean regeneration = true;
                File f = new File(avatarPath);
                String[] files = f.list(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        return name.startsWith("avatar-");
                    }
                });

                if (files.length > 0) {
                    files[0] = files[0].replace("avatar-", "");
                    files[0] = files[0].replace(".png", "");
                    if (!files[0].equals("")) {
                        int currentAvatarId = Integer.parseInt(files[0]);
                        System.out.println(universeImages.size() + " ==? " + currentAvatarId);
                        if (universeImages.size() == currentAvatarId) {
                            regeneration = false;
                        }
                    }
                }

                if (regeneration) { // genera il nuovo array
                    Collections.shuffle(universeImages); // mescolo l'arraylist per dare un risultato diverso ogni volta

                    int oldSize = universeImages.size();

                    if (universeImages.size() > 8) {
                        universeImages.subList(8, universeImages.size()).clear();
                    }

                    AvatarGenerator ag = new AvatarGenerator(avatarPath, universeImages, oldSize);
                    BufferedImage currentAvatar = ImageIO.read(new File(avatarPath +"avatar-" + oldSize +".png"));
                    ImageIO.write(currentAvatar, "png", new File(rootPath + "avatar/" + universe_id +".png"));
                    System.out.println("Path AG");
                    ArrayList<SimpleUniverse> oldList = (ArrayList<SimpleUniverse>) session.getAttribute("universeList");

                    Iterator<SimpleUniverse> simpleUniverseIterator = oldList.iterator();
                    SimpleUniverse editingUniverseAvatar = null;
                    while (simpleUniverseIterator.hasNext()) {
                        editingUniverseAvatar = simpleUniverseIterator.next();
                        if (editingUniverseAvatar.getIdUniverse() == universe_id) {
                            break;
                        }
                    }
                    editingUniverse.setAvatarPath("Universes/" + universe_id + "/avatar-" + oldSize + ".png");

                }

            }
            
            // ------------ FINE GENERAZIONE NUOVO AVATAR ------------
            
        } catch(Exception e) {            
            response.sendRedirect("/home.jsp");
        }
    }

    // <editor-fold desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
